// pages/admin/users/add/add.js
const app = getApp();

Page({
  data: {
    formData: {
      name: '',
      userId: '',
      role: 'student',
      department: '',
      departmentId: '',
      classId: '',
      phone: '',
      email: '',
      password: ''
    },
    roles: [
      { value: 'student', text: '学生' },
      { value: 'teacher', text: '教师' },
      { value: 'counselor', text: '辅导员' },
      { value: 'admin', text: '管理员' }
    ],
    roleIndex: 0,
    departments: [],
    departmentIndex: 0,
    classes: [],
    classIndex: 0,
    submitting: false
  },

  onLoad: function() {
    // 获取学院列表
    this.fetchDepartments();
  },

  // 获取学院列表
  fetchDepartments: function() {
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/departments`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('获取学院列表成功:', res.data);
          this.setData({
            departments: res.data,
            departmentIndex: 0
          });
          
          // 如果有学院数据，设置默认选中的学院
          if (res.data.length > 0) {
            this.setData({
              'formData.department': res.data[0].name,
              'formData.departmentId': res.data[0].id
            });
            
            // 获取该学院下的班级
            this.fetchClasses(res.data[0].id);
          }
        } else {
          wx.showToast({
            title: '获取学院列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取学院列表请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 获取班级列表
  fetchClasses: function(departmentId) {
    if (!departmentId) return;
    
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/classes`,
      method: 'GET',
      data: { departmentId: departmentId },
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('获取班级列表成功:', res.data);
          this.setData({
            classes: res.data,
            classIndex: 0
          });
          
          // 如果有班级数据，设置默认选中的班级
          if (res.data.length > 0) {
            this.setData({
              'formData.classId': res.data[0].id
            });
          }
        } else {
          wx.showToast({
            title: '获取班级列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取班级列表请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 输入框变化
  inputChange: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 角色选择变化
  roleChange: function(e) {
    const index = e.detail.value;
    const role = this.data.roles[index].value;
    
    this.setData({
      roleIndex: index,
      'formData.role': role
    });
  },

  // 学院选择变化
  departmentChange: function(e) {
    const index = e.detail.value;
    const department = this.data.departments[index];
    
    this.setData({
      departmentIndex: index,
      'formData.department': department.name,
      'formData.departmentId': department.id,
      classes: [],
      classIndex: 0,
      'formData.classId': ''
    });
    
    // 获取该学院下的班级
    this.fetchClasses(department.id);
  },

  // 班级选择变化
  classChange: function(e) {
    const index = e.detail.value;
    
    if (this.data.classes.length > 0) {
      this.setData({
        classIndex: index,
        'formData.classId': this.data.classes[index].id
      });
    }
  },

  // 取消添加
  cancelAdd: function() {
    wx.navigateBack();
  },

  // 提交表单
  submitForm: function() {
    // 表单验证
    if (!this.validateForm()) {
      return;
    }
    
    this.setData({ submitting: true });
    
    // 获取当前登录用户信息
    const currentUser = wx.getStorageSync('userInfo') || {};
    
    // 准备提交的数据
    const submitData = {
      name: this.data.formData.name,
      userId: this.data.formData.userId,
      role: this.data.formData.role,
      password: this.data.formData.password,
      department: this.data.formData.department,
      phone: this.data.formData.phone,
      email: this.data.formData.email,
      // 添加当前操作用户的信息，用于记录日志
      operatorName: currentUser.name || '',
      operatorId: currentUser.id || ''
    };
    
    // 如果是学生或辅导员，添加班级ID
    if (this.data.formData.role === 'student' || this.data.formData.role === 'counselor') {
      submitData.classId = this.data.formData.classId;
    }
    
    // 发送请求
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/users`,
      method: 'POST',
      data: submitData,
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '添加失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('添加用户请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ submitting: false });
      }
    });
  },

  // 表单验证
  validateForm: function() {
    const { name, userId, role, password, departmentId, classId } = this.data.formData;
    
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!userId) {
      wx.showToast({
        title: '请输入用户ID',
        icon: 'none'
      });
      return false;
    }
    
    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return false;
    }
    
    if (!departmentId) {
      wx.showToast({
        title: '请选择学院',
        icon: 'none'
      });
      return false;
    }
    
    if ((role === 'student' || role === 'counselor') && !classId) {
      wx.showToast({
        title: '请选择班级',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  }
});